package com.cfs.ipc;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Method;

import com.cfs.io.ObjectWritable;
import com.cfs.io.Writable;
import com.cfs.utils.UTF8;

public class Invocation implements Writable {

	private String methodName;
	private Class[] parameterClasses;
	private Object[] parameters;

	public Invocation() {

	}

	public Invocation(Method method, Object[] parameters) {
		this.methodName = method.getName();
		this.parameterClasses = method.getParameterTypes();
		this.parameters = parameters;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setParameterClasses(Class[] parameterClasses) {
		this.parameterClasses = parameterClasses;
	}

	public Class[] getParameterClasses() {
		return parameterClasses;
	}

	public void setParameters(Object[] parameters) {
		this.parameters = parameters;
	}

	public Object[] getParameters() {
		return parameters;
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		this.methodName = UTF8.readString(in);
		this.parameters = new Object[in.readInt()];
		parameterClasses = new Class[parameters.length];
		ObjectWritable objectWritable = new ObjectWritable();
		for (int i = 0; i < parameters.length; i++)
		{
			parameters[i] = ObjectWritable.readObject(in, objectWritable);
			parameterClasses[i] = objectWritable.getDeclaredClass();
		}
	}

	@Override
	public void write(DataOutput out) throws IOException {
		UTF8.writeString(out, methodName);
		out.writeInt(parameterClasses.length);
		for (int i = 0; i < parameterClasses.length; i++)
		{
			ObjectWritable.writeObject(out, parameters[i], parameterClasses[i]);
		}
	}

	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(methodName);
		buffer.append("(");
		if(parameters != null && parameters.length > 0) {
			for (int i = 0; i < parameters.length; i++) {
				if (i != 0)
					buffer.append(", ");
				buffer.append(parameters[i]);
			}
		}
		buffer.append(")");
		return buffer.toString();
	}

}
